import { reqCartList, reqDeleteCateById, reqUpdateCheckedById } from "@/api";

const state = {
  cartList: [],
};
const actions = {
  //得到数据
  async getCartList({ commit }) {
    let result = await reqCartList();
    if (result.code == 200) {
      commit("GETCARTLIST", result.data);
    }
  },
  //删除某个产品
  async deleteCartListBySkuId({ commit }, skuId) {
    let result = await reqDeleteCateById(skuId);
    if (result.code == 200) {
      return result.data;
    } else {
      return Promise.reject(new Error("no"));
    }
  },
  //修改某个产品的勾选状态
  async updateCheckedById({ commit }, { skuId, isChecked }) {
    let result = await reqUpdateCheckedById(skuId, isChecked);
    if (result.code == 200) {
      return "ok";
    } else {
      return Promise.reject(new Error("no"));
    }
  },
  //删除选中的全部商品
  deleteAllCheckedCart({ dispatch, getters }) {
    let promise = [];
    getters.cartList.cartInfoList.forEach((item) => {
      if (item.isChecked == 1) {
        let pro = dispatch("deleteCartListBySkuId", item.skuId);
        promise.push(pro);
      }
    });
    return Promise.all(promise);
  },
  //全选按钮
  checkAll({ dispatch, getters }, isChecked) {
    let promise = [];
    getters.cartList.cartInfoList.forEach((item) => {
      if (item.isChecked != isChecked) {
        let pro = dispatch("updateCheckedById", {
          skuId: item.skuId,
          isChecked,
        });
        promise.push(pro);
      }
    });
    return Promise.all(promise);
  },
};
const mutations = {
  GETCARTLIST(state, data) {
    state.cartList = data;
  },
};
const getters = {
  cartList(state) {
    return state.cartList[0] || {};
  },
};
export default {
  actions,
  state,
  mutations,
  getters,
};
